<?php

class RemotetoolkitComponent extends Object
{
	var $socket;
	var $remotetoolkit;
	
	function initialize(&$controller, $settings = array()) {
		// saving the controller reference for later use
		$this->controller =& $controller;
	}
	
	function createSocket()
	{
		$this->remotetoolkit['server'] = Configure::read('bukkitadmin.RemoteToolkitServer');
		$this->remotetoolkit['port'] = Configure::read('bukkitadmin.RemoteToolkitPort');
		$this->remotetoolkit['pass'] = Configure::read('bukkitadmin.RemoteToolkitPassword');
		$this->remotetoolkit['user'] = Configure::read('bukkitadmin.RemoteToolkitUser');
		$this->socket = fsockopen('udp://'.Configure::read('bukkitadmin.RemoteToolkitServer'), Configure::read('bukkitadmin.RemoteToolkitPort'), $errno, $errstr,3);
		if(!$this->socket)
		{
			return FALSE;			
		}
		else
		{
			if($this->cmd('version')==FALSE)
			{
				return FALSE;
			}
			else
			{
				return TRUE;
				}		
		}
	}
	
	//called after Controller::beforeFilter()
	function startup(&$controller) {
	}
	
	//called after Controller::beforeRender()
	function beforeRender(&$controller) {
	}
	
	//called after Controller::render()
	function shutdown(&$controller) {
	}
	
	//called before Controller::redirect()
	function beforeRedirect(&$controller, $url, $status=null, $exit=true) {
	}
	
	public function cmd($cmd,$log=false)
	{
		if (!$this->socket)
		{
			$result = FALSE;
		}
		else
		{
			fwrite($this->socket, $cmd.':'.$this->remotetoolkit['user'].':'.$this->remotetoolkit['pass']);
			stream_set_timeout($this->socket,3);
			$result = fread($this->socket, 128);
		}
		return $result;
	}
	
	public function getUsers()
	{
		
	}
	
	public function sendCmd($cmd)
	{
		$this->remotetoolkit['server'] = Configure::read('bukkitadmin.RemoteToolkitServer');
		$this->remotetoolkit['port'] = Configure::read('bukkitadmin.RemoteToolkitPort');
		$this->remotetoolkit['pass'] = Configure::read('bukkitadmin.RemoteToolkitPassword');
		$this->remotetoolkit['user'] = Configure::read('bukkitadmin.RemoteToolkitUser');
		
		$fp = fsockopen($this->remotetoolkit['server'], $this->remotetoolkit['port'],$errno, $errstr,3);
		if(!$fp)
		{
			return FALSE;
		}
		else
		{
			fwrite($fp, "\r\n".$this->remotetoolkit['user']."\n");
			fwrite($fp, $this->remotetoolkit['pass']."\n");
			fwrite($fp, $cmd."\n");
			$read = array($fp);
			$write = array();
			$except = array();
			while(stream_select($read, $write, $except, 1, 1000))
				$result .= fgets($read[0]);

			/*stream_set_timeout($fp, 0, 1000);
			while (($buffer = fgets($fp, 4096)) !== false) {
				echo $buffer;
			}
			if (!feof($fp)) {
				echo "Erreur: fgets() a échoué\n";
			}*/
			fclose($fp);
			return $result;
		}
	}
}
?>